﻿using Heima.OA.IBLL;
using Heima.OA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Heima.OA.BLL
{
    public partial class UserInfoService : BaseService<UserInfo>, IUserInfoService
    {
        public bool SetRole(int userId, List<int> roleIds)
        {
            //GetEntities(u => u.Id == id).FirstOrDefault(); GetModel(userId)
            var user = DbSession.UserInfoDal.GetEntities(u => u.Id == userId).FirstOrDefault();
            user.RoleInfo.Clear();//删除用户所有的角色关系
            var allRoles = DbSession.RoleInfoDal.GetEntities(r => roleIds.Contains(r.Id));
            foreach(var role in allRoles)
            {
                user.RoleInfo.Add(role);//用户添加最新的角色关系
            }
            return DbSession.SaveChanges()>0;
        }
        /// <summary>
        /// 设置用户部门
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="deptIds"></param>
        /// <returns></returns>
        public bool SetDept(int userId, List<int> deptIds)
        {
            var userDeptList = DbSession.UserDepartmentDal.GetEntities(u => u.UserId == userId).ToList();
            foreach(var item in userDeptList)
            {
                DbSession.UserDepartmentDal.Delete(item.Id);
            }
            foreach(var deptId in deptIds)
            {
                UserDepartment userDept = new UserDepartment();
                userDept.UserId = userId;
                userDept.DeptId = deptId;
                DbSession.UserDepartmentDal.Add(userDept);
            }
            return DbSession.SaveChanges() > 0;
        }

    }
}
